<template>
  <div class="dhcc-body">
    <el-row :gutter="10">
      <el-col :span="4">
        <div class="dhcc-tree" style="height: 650px">
          <!-- 树形数据 -->
          <el-tree
            :data="data"
            :props="defaultProps"
            highlight-current
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
            node-key="id"
            :default-expanded-keys="['ROOT']"
          ></el-tree>
        </div>
      </el-col>
      <el-col :span="20">
        <div class="dhcc-search">
          <!-- 检索区 -->
          <el-form
            :model="searchMap"
            class="demo-form-inline"
            size="mini"
            :inline="true"
          >
            <el-form-item prop="status">
              <el-radio-group v-model="searchMap.status" @change="chageStatus">
                <el-radio label="1">启用</el-radio>
                <el-radio label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="handleAdd"
                size="mini"
                icon="el-icon-plus"
                >新建</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="dhcc-main">
          <!-- 表格数据 -->
          <el-table
            :data="list"
            height="550"
            border
            style="width: 100%"
            size="mini"
          >
            <el-table-column
              type="index"
              label="序号"
              width="60"
            ></el-table-column>

            <el-table-column prop="id" label="编号"></el-table-column>
            <el-table-column prop="name" label="名称"></el-table-column>
            <el-table-column prop="type" label="类型">
              <template slot-scope="scope">
                <span>{{ scope.row.type | pathTypeFilter }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="pid" label="上级编码"></el-table-column>
            <el-table-column prop="pname" label="上级名称"></el-table-column>
            <el-table-column prop="status" label="状态" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.status | statusFilter }}</span>
              </template>
            </el-table-column>
            <el-table-column label="启用/停用" width="80" align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="warning"
                  @click="handleIsDisplay(scope.row.id, scope.row.status)"
                  >{{ scope.row.status == 1 ? "停用" : "启用" }}</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" align="center">
              <template slot-scope="scope">
                <el-button size="mini" @click="handleEdit(scope.row.id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDele(scope.row.id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页显示 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-col>
    </el-row>
    <!-- 弹出新增窗口 -->
    <el-dialog title="程序编辑" :visible.sync="dialogFormVisible" width="500px">
      <el-form
        ref="pojoForm"
        :rules="rules"
        label-width="100px"
        label-position="right"
        :model="pojo"
        style="width: 400px"
        size="mini"
      >
        <el-form-item label="程序代码" prop="id">
          <el-input v-model="pojo.id" :disabled="saveFlg"></el-input>
        </el-form-item>
        <el-form-item label="程序名称" prop="name">
          <el-input v-model="pojo.name" @blur="handleBlur"></el-input>
        </el-form-item>
        <el-form-item label="简拼" prop="py">
          <el-input v-model="pojo.py"></el-input>
        </el-form-item>
        <el-form-item label="顺序号" prop="seq">
          <el-input v-model="pojo.seq" type="number"></el-input>
        </el-form-item>
        <el-form-item label="程序类型" prop="type">
          <el-select
            v-model="pojo.type"
            placeholder="程序类型"
            style="width: 100%"
          >
            <el-option
              v-for="option in pathTypeOptions"
              :key="option.type"
              :label="option.name"
              :value="option.type"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="程序路径" prop="url">
          <el-input v-model="pojo.url"></el-input>
        </el-form-item>
        <el-form-item label="重定向路径" prop="redirect">
          <el-input v-model="pojo.redirect"></el-input>
        </el-form-item>
        <el-form-item label="程序图标" prop="icon">
          <el-input v-model="pojo.icon"></el-input>
        </el-form-item>
        <el-form-item label="组件名称" prop="icon">
          <el-input v-model="pojo.component"></el-input>
        </el-form-item>
        <el-form-item label="是否缓存" prop="nocache">
          <el-switch
            v-model="pojo.nocache"
            active-value="1"
            inactive-value="0"
          ></el-switch>
        </el-form-item>
        <el-form-item label="父节点代码" prop="payType">
          <el-select
            v-model="pojo.pid"
            filterable
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="option in pathSelect"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="程序状态" prop="status" hidden>
          <el-input v-model="pojo.status"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="mini"
          >取 消</el-button
        >
        <el-button
          type="primary"
          size="mini"
          @click="!saveFlg ? addData('pojoForm') : updateData('pojoForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  pathTree,
  search,
  updateStatus,
  add,
  getById,
  update,
  deleteById,
  listSelect,
} from "@/api/sys/sysPagePath";
import vPinyin from "@/utils/py";
import app from "@/store/modules/app.js";

// 程序类型
const pathTypeOptions = [
  { type: 1, name: "文件夹" },
  { type: 2, name: "程序" },
  { type: 3, name: "权限" },
];
// 状态类型
const statusOptions = [
  { type: 0, name: "停用" },
  { type: 1, name: "启用" },
];

export default {
  name: "sysPagePath",
  data() {
    return {
      list: [],
      total: 0, // 总记录数
      currentPage: 1, // 当前页, 默认第1页
      pageSize: 10, // 每页显示条数， 10条
      data: [],
      pathSelect: [],
      defaultProps: {
        id: "id",
        children: "children",
        label: "name",
        type: "type",
      }, // 树形结构
      searchMap: {
        name: "",
        type: null,
        pid: "",
        status: "1",
      }, // 条件查询绑定条件值
      pojo: {
        id: null,
        name: "",
        py: "",
        seq: 0,
        type: 1,
        url: "",
        redirect: "",
        icon: "",
        nocache: 0,
        component: "",
        pid: null,
        status: 1,
      }, // 提交的数据
      pathTypeOptions: pathTypeOptions, // 程序类型，ES6语法
      statusOptions: statusOptions, // 状态类型
      dialogFormVisible: false, // 控制对话框
      saveFlg: false, // 新增/更新状态 false: 新增； true：更新
      rules: {
        // 校验规则
        id: [
          {
            required: true,
            message: "程序代码不能为空",
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: "程序名称不能为空",
            trigger: "blur",
          },
        ],
        seq: [
          {
            required: true,
            message: "顺序号不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.fetchData();
    // 控制左侧导航栏是否展开
    // app.state.sidebar.opened = false;
  },
  methods: {
    // 查询功能
    fetchData() {
      pathTree().then((response) => {
        const resp = response;
        if (resp.flag) {
          this.data = response.data;
        } else {
          // 查询失败
          this.$message({ message: resp.message, type: "warning" });
        }
      });
    },
    // 查询程序子集合数据
    handleNodeClick(data) {
      this.searchMap.pid = data.id;
      this.searchMap.type = data.type;
      this.searchData(this.searchMap);
    },
    // 当每页条数改变后触发
    handleSizeChange(val) {
      this.pageSize = val;
      this.searchData(this.searchMap);
    },
    // 当页码改变后触发
    handleCurrentChange(val) {
      this.currentPage = val;
      this.searchData(this.searchMap);
    },
    // 启用/停用按钮
    handleIsDisplay(id, status) {
      this.$confirm(
        status === 1 ? "确认停用这条记录吗?" : "确认启用这条记录吗?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          // 确认
          updateStatus(id, status).then((response) => {
            const resp = response;
            if (resp.flag) {
              // 更新成功, 刷新列表数据
              this.searchData(this.searchMap);
              this.$message({ message: resp.message, type: "success" });
            } else {
              // 更新失败
              this.$message({ message: resp.message, type: "warning" });
            }
          });
        })
        .catch(() => {
          // 取消
        });
    },
    // 切换状态按钮
    chageStatus() {
      this.searchData(this.searchMap);
    },
    // 生成拼音
    handleBlur() {
      this.pojo.py = vPinyin.getFirstLettersUpper(this.pojo.name);
    },
    // 查询数据
    searchData(map) {
      search(this.currentPage, this.pageSize, map).then((response) => {
        const reqs = response;
        this.total = reqs.data.total;
        this.list = reqs.data.rows;
      });
    },
    // 弹出新增程序
    handleAdd() {
      this.dialogFormVisible = true;
      this.saveFlg = false;
      this.$nextTick(() => {
        // 异步事件
        this.$refs["pojoForm"].resetFields();
        this.pojo.id = null;
        if (this.searchMap.type == null) {
          this.pojo.type = 1;
        } else if (this.searchMap.type == 1) {
          this.pojo.type = 2;
        } else if (this.searchMap.type == 2) {
          this.pojo.type = 3;
        } else {
          this.pojo.type = 1;
        }
        this.pojo.status = 1;
        // 查询程序下拉框数据
        listSelect().then((response) => {
          const resp = response;
          if (resp.flag) {
            this.pathSelect = response.data;
          }
          if (this.searchMap.pid === "ROOT" || this.searchMap.pid === "") {
            this.pojo.pid = null;
          } else {
            this.pojo.pid = this.searchMap.pid;
          }
        });
      });
    },
    // 提交新增数据
    addData(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          add(this.pojo).then((response) => {
            const resp = response;
            if (resp.flag) {
              // 新增成功, 刷新列表数据
              this.fetchData();
              this.searchData(this.searchMap);
              this.dialogFormVisible = false; //关闭窗口
              this.$message({ message: resp.message, type: "success" });
            } else {
              // 新增失败
              this.$message({ message: resp.message, type: "warning" });
            }
          });
        } else {
          return false;
        }
      });
    },
    // 提交更新数据
    updateData(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          update(this.pojo).then((response) => {
            const resp = response;
            if (resp.flag) {
              // 更新成功, 刷新列表数据
              this.fetchData();
              this.searchData(this.searchMap);
              this.dialogFormVisible = false; //关闭窗口
              this.$message({ message: resp.message, type: "success" });
            } else {
              this.$message({ message: resp.message, type: "warning" });
              // 更新失败
            }
          });
        } else {
          return false;
        }
      });
    },
    // 编辑功能
    handleEdit(id) {
      this.handleAdd();
      this.saveFlg = true;
      getById(id).then((response) => {
        const resp = response;
        if (resp.flag) {
          this.pojo = resp.data;
          if (this.pojo.nocache == 0) {
            this.pojo.nocache = "0";
          } else {
            this.pojo.nocache = "1";
          }
        } else {
          this.$message({ message: resp.message, type: "warning" });
        }
      });
    },
    // 删除功能
    handleDele(id) {
      this.$confirm("确认删除这条记录吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 确认
          deleteById(id).then((response) => {
            const resp = response;
            this.$message({
              message: resp.message,
              type: resp.flag ? "success" : "error",
            });
            if (resp.flag) {
              this.fetchData();
              this.searchData(this.searchMap);
            }
          });
        })
        .catch(() => {
          // 取消
        });
    },
  },
  filters: {
    // filters 中 this 指向的不是vue实例, 所有无法直接获取 data 中的数据
    pathTypeFilter(type) {
      // 全局的 pathTypeOptions , 返回一个满足条件的对象
      const obj = pathTypeOptions.find((obj) => obj.type === type);
      // 非空返回类型名称
      return obj ? obj.name : null;
    },
    // filters 中 this 指向的不是vue实例, 所有无法直接获取 data 中的数据
    statusFilter(type) {
      // 全局的 statusOptions , 返回一个满足条件的对象
      const obj = statusOptions.find((obj) => obj.type === type);
      // 非空返回类型名称
      return obj ? obj.name : null;
    },
  },
};
</script>

<style>
</style>